//
//  MBMineDataManager.m
//  Meboo
//
//  Created by kyo on 2023/10/16.
//

#import "MBMineDataManager.h"
#import "MBHTTPNetworking.h"
@implementation MBMineDataManager
+ (MBMineDataManager *)sharedManager {
    static dispatch_once_t onceToken;
    static MBMineDataManager *obj;
    dispatch_once(&onceToken, ^{
        obj = [[self alloc] init];
    });
    return obj;
}

#pragma mark -用户注销
- (void)logOut:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/auth/logout" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSLog(@"");
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -获取用户interests列表
- (void)getInterests:(void(^)(BOOL success))resultBlock {
    __WeakSelf
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/users/interests" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSLog(@"");
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            NSArray *dataArr = responseObject[@"data"];
            [weakSelf.interestsArr removeAllObjects];
            MBUserAccount *account = [MBUserAccount defaultAccount];
            for (NSDictionary *dict in dataArr) {
                KLInterestsModel *model = [KLInterestsModel mj_objectWithKeyValues:dict];
                for (int i = 0; i < account.interests.count; i++) {
                    NSString *codeStr = account.interests[i];
                    if ([model.interest isEqualToString:codeStr]) {
                        model.selected = YES;
                        break;
                    }
                }
                
                [weakSelf.interestsArr addObject:model];
            }
            
            
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -更改个人信息
- (void)changeUserInfoWithKey:(NSString *)key value:(id)value Success:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:value forKey:key];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/users/changeUserInfo" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

- (void)saveUserInfoWithName:(NSString *)name about:(NSString *)about interests:(NSArray *)interests  Success:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:name forKey:@"nickName"];
    [params setObject:about forKey:@"aboutMe"];
    [params setObject:interests forKey:@"interests"];
    [params setObject:[MBUserAccount defaultAccount].images forKey:@"images"];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/users/changeUserInfo" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -支付校验
/**
 返回三个状态
 0：成功验单
 1：请求成功了，但是验单没有成功
 2：请求失败
 */
- (void)checkApplePayWith:(NSString *)productCode orderNo:(NSString *)orderNo orderId:(NSString *)orderId payReceipt:(NSString *)payReceipt  Success:(void(^)(NSInteger state))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:payReceipt ?: @"" forKey:@"payReceipt"];
    [params setObject:orderNo ?: @"" forKey:@"orderNo"];
    [params setObject:productCode ?: @"" forKey:@"productCode"];
    [params setObject:orderId forKey:@"orderId"];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/order/apple/pay/success" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            [self paySuccessNoti:productCode];
            if (resultBlock) resultBlock(0);
        } else {
            if (resultBlock) resultBlock(1);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(2);
    }];
}

#pragma mark -获取vip享受的权益列表
- (void)getVipEquity:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/member/product/subscription" method:@"GET" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -获取私密相册/fc信息
- (void)getUserPrivateInfo:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/member/queryBenefits" method:@"GET" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            [self.privateArr removeAllObjects];
            MBUserAccount *account = [MBUserAccount defaultAccount];
            
            NSArray *dataArr = responseObject[@"data"];
            if (dataArr != nil && dataArr != NULL && [dataArr isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dict in dataArr) {
                    NSVipInfonModel *model = [NSVipInfonModel mj_objectWithKeyValues:dict];
                    [self.privateArr addObject:model];
                    if (model.benefitCode == 1) {
                        account.fcNum = model.maxUses;
                    } else if (model.benefitCode == 2) {
                        account.ppNum = model.maxUses;
                    } else if (model.benefitCode == 3) {
                        account.pvNum = model.maxUses;
                    }
                }
                [MBUserAccount saveAccount:account];
            }
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -消费 pp/pv/fc接口
/**
 benefitCode：1-fc 2-pp 3-pv
 benefitName：权益名称
 chatUserCode：Model Code
 msgId：聊天过程中触发的必须传递msgId
 imageCode：ppv必传
 imageUrl：ppv必传
 */
- (void)payWithType:(NSInteger)type chatUserCode:(NSString *)userCode msgId:(NSString *)msgId imageCode:(NSString *)imageCode imageUrl:(NSString *)imageUrl success:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@(type) forKey:@"benefitCode"];
    [params setObject:userCode forKey:@"chatUserCode"];
    [params setObject:msgId forKey:@"msgId"];
    [params setObject:imageCode forKey:@"imageCode"];
    [params setObject:imageUrl forKey:@"imageUrl"];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/benefits/reduceBenefits" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            //消费成功 手动减一
            MBUserAccount *account = [MBUserAccount defaultAccount];
            if (type == 1) {
                account.fcNum -= 1;
            } else if (type == 2) {
                account.ppNum -= 1;
            } else if (type == 3) {
                account.pvNum -= 1;
            }
            [MBUserAccount saveAccount:account];
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -获取会员产品列表接口
/**
 productCategory：0:所有产品 1-会员 2-fc 3-pp 4-pv
 */
- (void)getMemberProductWithType:(NSInteger)type success:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@(type) forKey:@"productCategory"];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/member/product/category" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 0) {
            if (type == 11) {
                [self.vipProductArr removeAllObjects];
                [self.vipEquityArr removeAllObjects];
            } else if (type == 2) {
                [self.fcProductArr removeAllObjects];
            } else if (type == 3) {
                [self.ppProductArr removeAllObjects];
            } else if (type == 4) {
                [self.pvProductArr removeAllObjects];
            }
//            [self.productArr removeAllObjects];
            NSArray *dataArr = responseObject[@"data"][@"productDescriptions"];
            for (NSDictionary *dict in dataArr) {
                NSProductModel *model = [NSProductModel mj_objectWithKeyValues:dict];
                if (type == 11) {
                    [self.vipProductArr addObject:model];
                } else if (type == 2) {
                    [self.fcProductArr addObject:model];
                } else if (type == 3) {
                    [self.ppProductArr addObject:model];
                } else if (type == 4) {
                    [self.pvProductArr addObject:model];
                }
//                [self.productArr addObject:model];
            }
            
            NSArray *dataArr1 = responseObject[@"data"][@"subscriptions"];
            for (NSDictionary *dict in dataArr1) {
                MBVipEquityModel *model = [MBVipEquityModel mj_objectWithKeyValues:dict];
                if (type == 11) {
                    [self.vipEquityArr addObject:model];
                }
            }
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

#pragma mark -获取商品id (支付去苹果校验之前,先请求后端接口获得商品id)
/**
 productCategory：1-会员 2-fc 3-pp 4-pv
 */
- (void)getProductIdWithType:(NSInteger)type productCode:(NSString *)productCode modelUserCode:(NSString *)modelUserCode success:(void(^)(BOOL success))resultBlock {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:@(type) forKey:@"productCategory"];
    [params setObject:modelUserCode ?: @"" forKey:@"modelUserCode"];
    [params setObject:productCode ?: @"" forKey:@"productCode"];
    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"api/order/generateOrder" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"code"] integerValue];
        self.orderNo = @"";
        if (code == 0) {
            self.orderNo = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"orderNo"]];
            if (resultBlock) resultBlock(YES);
        } else {
            if (resultBlock) resultBlock(NO);
        }
    } failure:^(NSError * _Nullable error) {
        if (resultBlock) resultBlock(NO);
    }];
}

- (void)paySuccessNoti:(NSString *)productCode {
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    if ([productCode containsString:@"meboo_vip"]) {
        dispatch_group_enter(group);
        dispatch_group_async(group, queue, ^{
            [[MBLoginDataManager sharedManager] getUserInfoWithCode:@"" success:^(BOOL success) {
                dispatch_group_leave(group);
            }];
        });
    }
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [self getUserPrivateInfo:^(BOOL success) {
            dispatch_group_leave(group);
        }];
    });
    
    //调度组 全部加载完成之后的回调
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBNotificationCenter postNotificationName:PAY_SUCCESS_NOTIFICATION object:nil];
        });
    });
}


- (NSMutableArray *)interestsArr {
    if (!_interestsArr) {
        _interestsArr = [NSMutableArray array];
    }
    return _interestsArr;
}

- (NSMutableArray<MBVipEquityModel *> *)vipEquityArr {
    if (!_vipEquityArr) {
        _vipEquityArr = [NSMutableArray array];
    }
    return _vipEquityArr;
}

- (NSMutableArray<NSVipInfonModel *> *)privateArr {
    if (!_privateArr) {
        _privateArr = [NSMutableArray array];
    }
    return _privateArr;
}

//- (NSMutableArray<NSProductModel *> *)productArr {
//    if (!_productArr) {
//        _productArr = [NSMutableArray array];
//    }
//    return _productArr;
//}

- (NSMutableArray<NSProductModel *> *)vipProductArr {
    if (!_vipProductArr) {
        _vipProductArr = [NSMutableArray array];
    }
    return _vipProductArr;
}

- (NSMutableArray<NSProductModel *> *)fcProductArr {
    if (!_fcProductArr) {
        _fcProductArr = [NSMutableArray array];
    }
    return _fcProductArr;
}

- (NSMutableArray<NSProductModel *> *)ppProductArr {
    if (!_ppProductArr) {
        _ppProductArr = [NSMutableArray array];
    }
    return _ppProductArr;
}

- (NSMutableArray<NSProductModel *> *)pvProductArr {
    if (!_pvProductArr) {
        _pvProductArr = [NSMutableArray array];
    }
    return _pvProductArr;
}
@end
